package com.huawei.petapp2.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huawei.petapp2.R;
import com.huawei.petapp2.activity.MineCenterActivity;
import com.huawei.petapp2.activity.SearchActivity;
import com.huawei.petapp2.adapter.TestGoodAdapter;
import com.huawei.petapp2.constant.HttpAddress;
import com.huawei.petapp2.entity.Recomment;
import com.huawei.petapp2.entity.Result;
import com.huawei.petapp2.utils.DateUtil;
import com.huawei.petapp2.utils.GlideImageLoader;
import com.youth.banner.Banner;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by 吕氏春秋i 2020/4/30
 * Describe:
 */


public class HomeFragment extends BaseFragment {
    SQLiteDatabase databases;
    private LinearLayout mToolbar;
    private RecyclerView mRecyclerView;
    private AppCompatImageView tvNews;
  // private List<Petshow> data;
    private List <Recomment>recomments;
   // private List<TestBean> data;
    private int height;

    View rootView;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_home;
    }



    @Override
    public void initView(View mView) {
        mToolbar = mView.findViewById(R.id.toolbar);
        mRecyclerView = mView.findViewById(R.id.app_home_list);
        tvNews=mView.findViewById(R.id.app_home_title_tv_news);
        tvNews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getContext(), SearchActivity.class);
                startActivity(intent);
            }
        });
        mToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(getContext(), MineCenterActivity.class);
                startActivity(intent);
            }
        });
        lazyLoad();
    }

    @Override
    public void lazyLoad() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 6);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        /*MyDBOpenHelper db = new MyDBOpenHelper((BaseActivity) mRecyclerView.getContext());
        databases= openOrCreateDatabase("goods_store.db",(BaseActivity) mRecyclerView.getContext(), null);
        goodsDao=new GoodsDao(databases);
        data = goodsDao.enquiry_goods();*/
        //  List<Petshow> petshow=DateUtil.getList(results);
        //System.out.println(users.toString());
        //System.out.println(petshow.get(0));
       /* data = new Gson().fromJson(String.valueOf(results), new TypeToken<List<Result>>() {
        }.getType());*/
        /*Result results =DateUtil.selectList(
                HttpAddress.get(HttpAddress.petshow(),"show"));*/
       /* String jsonData = new String(getAssertsFile(getContext(), "content.json"));
        data = new Gson().fromJson(jsonData, new TypeToken<List<TestBean>>() {
        }.getType());

        System.out.println("商品json数据转换"+data);
        TestHomeAdapter adapter = new TestHomeAdapter();*/
        Result result = DateUtil.selectList(
                HttpAddress.get(HttpAddress.Category(),"list-recommends"));//获取首页的新品推荐

        recomments=DateUtil.getList6(result);

        System.out.println(recomments);
        TestGoodAdapter adapter = new TestGoodAdapter();

        adapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
              // int type = data.get(position).getType();

                int type = recomments.get(position).getType();
                System.out.println("图片类型" +type);
                if (type == 1 || type == 3 || type == 2 || type == 5 || type == 6) {
                    return 6;
                } else if (type == 4) {
                    return 2;
                } else if (type == 7) {
                        return 3;
                    }
                return 0;
            }
        });
        /*Result result = DateUtil.selectList(
                HttpAddress.get(HttpAddress.user(),"list"));

        List<User> users=DateUtil.getList(result);*/
        mRecyclerView.setAdapter(adapter);
        adapter.setHeaderView(getHeaderView(mRecyclerView));
        adapter.setNewData(recomments);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int totalDy = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy += dy;
                if (totalDy <= height) {
                    float alpha = (float) totalDy / height;
                    mToolbar.setBackgroundColor(ColorUtils.blendARGB(Color.TRANSPARENT
                            , ContextCompat.getColor(getContext(), R.color.white), alpha));
                } else {
                    mToolbar.setBackgroundColor(ColorUtils.blendARGB(Color.TRANSPARENT
                            , ContextCompat.getColor(getContext(), R.color.white), 1));
                }
            }
        });
    }

    private View getHeaderView(RecyclerView v) {
        List<String> bannerImg = new ArrayList<>();
        bannerImg.add("http://pic5.photophoto.cn/20071024/0035035948722934_b.jpg");
        bannerImg.add("https://p5.ssl.qhimgs1.com/sdr/400__/t0174467dd314977b4f.jpg");
        bannerImg.add("http://www.goupuzi.com/attachment/Mon_1708/2_168303_bdb41f0b3fe4a6b.jpg");
        bannerImg.add("https://p0.ssl.qhimgs4.com/t0169b4866e266694eb.jpg");
        View convertView = LayoutInflater
                .from(getContext())
                .inflate(R.layout.app_include_home_header, (ViewGroup) v.getParent(), false);
        Banner mBanner = convertView.findViewById(R.id.app_home_header_banner);
        mBanner.setImages(bannerImg)
                .setImageLoader(new GlideImageLoader())
                .setDelayTime(3000)
                .start();


       /* MarqueeView marqueeView = convertView.findViewById(R.id.app_home_header_problem);

        List<String> problems = new ArrayList<>();
        problems.add("如何发帖评论");
        problems.add("下单时服务费率规则");
        problems.add("大额预定商品详细交易流程");
        problems.add("如何在线下单点餐");
        marqueeView.startWithList(problems);*/

        ViewGroup.LayoutParams bannerParams = mBanner.getLayoutParams();
        int resourceId = getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = getContext().getResources().getDimensionPixelSize(resourceId);
        height = bannerParams.height - statusBarHeight - 104;

        return convertView;
    }


    public static byte[] getAssertsFile(Context context, String fileName) {
        InputStream inputStream = null;
        AssetManager assetManager = context.getAssets();
        try {
            inputStream = assetManager.open(fileName);
            if (inputStream == null) {
                return null;
            }

            BufferedInputStream bis = null;
            int length;
            try {
                bis = new BufferedInputStream(inputStream);
                length = bis.available();
                byte[] data = new byte[length];
                bis.read(data);

                return data;
            } catch (IOException e) {

            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (Exception e) {

                    }
                }
            }

            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
